import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flutter/material.dart';
import 'package:flutter_flame/worlds/game/state/SeedSelectionState.dart';
import 'SeedBank.dart';
import 'SeedChooserBackground.dart';
import 'SeedPacket.dart';
import 'SeedPacketSilhouette.dart';

// 种子商店 - 此处开始
class SeedChooserBank extends PositionComponent {
  static const int _colCount = 8;
  static const int _rowCount = 5;
  static const double _startX = 27;
  static const double _startY = -30;
  static const double _gap = 4;
  static const double _tileWidth = 60.0;
  static const double _offsetY = 190.0;
  static const double _rightOffsetX = 500;
  static const double _leftOffsetX = 30.0;

  late final SeedBank seedBank;
  late final SeedChooserBackground seedChooserBackground; // 背景
  VoidCallback onCompleted;
  SeedSelectionState state;

  SeedChooserBank({
    required this.onCompleted,
    required this.state,
  });

  @override
  Future<void> onLoad() async {
    position = Vector2(_rightOffsetX, _offsetY);
    seedBank = SeedBank(state: state);
    add(seedBank);
    seedBank.moveIn();
    seedChooserBackground = SeedChooserBackground(state: state); // 背景
    add(seedChooserBackground);
    seedChooserBackground.moveIn(displaySeeds);
    return super.onLoad();
  }

  void readyForFight() {
    add(
      MoveToEffect(
        Vector2(_leftOffsetX, _offsetY),
        EffectController(
          duration: 2,
          curve: Curves.easeInOut,
        ),
      ),
    );
  }

  // 显示所有种子
  void displaySeeds() {
    for (int i = 0; i < _colCount; i++) {
      for (int j = 0; j < _rowCount; j++) {
        _createSilhouette(i, j);
        final index = i + j * _colCount;
        if (index < state.seeds.length) {
          _createSeedPacket(i, j, index);
        }
      }
    }
  }

  void _createSilhouette(i, j) {
    final seed = SeedPacketSilhouette(
      i: i,
      j: j,
      startX: _startX,
      startY: _startY,
      gap: _gap,
    );
    add(seed);
  }

  void _createSeedPacket(int i, int j, int index) {
    state.seeds[index].initPosition = Vector2(
      _startX + i * (_tileWidth + _gap),
      _startY + (_tileWidth / (50 / 70) + _gap * 2) * j,
    );
    addAll([
      SeedPacket(
        i: i,
        j: j,
        startX: _startX,
        startY: _startY,
        gap: _gap,
        index: index,
        showShadow: true,
        isSeedBackground: true,
        state: state,
      ),
      SeedPacket(
        i: i,
        j: j,
        startX: _startX,
        startY: _startY,
        gap: _gap,
        index: index,
        startBtnBg: seedChooserBackground.startButtonBackground,
        state: state,
      )
    ]);
  }
}
